package org.example.util;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONObject;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class QRUtil {

    private static final String IMAGE_BASE64_PREFIX_PATTERN = "data:image/(jpg|jpeg|png);base64,";

    public static String getBarCode(String content) {
        BufferedImage image = QrCodeUtil.generate(content, BarcodeFormat.CODE_128, 200, 50);
        String result = ImgUtil.toBase64DataUri(image, ImgUtil.IMAGE_TYPE_JPG);
        return result;
    }

    public static String getQrCode(String content){
        // 生成二维码到文件，也可以到流
        BufferedImage image = QrCodeUtil.generate(content, new QrConfig());
        String result = QrCodeUtil.generateAsBase64(content, new QrConfig(), ImgUtil.IMAGE_TYPE_JPG);
        return result;
    }

    public static JSONObject QRReader(String content) throws IOException, NotFoundException {
        JSONObject resultJson = new JSONObject();
        byte[] imageBytes = Base64.getDecoder().decode(content);
        MultiFormatReader formatReader = new MultiFormatReader();
        //读取指定的二维码文件
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        BinaryBitmap binaryBitmap= new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
        //定义二维码参数
        Map hints= new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        com.google.zxing.Result result = formatReader.decode(binaryBitmap, hints);
        resultJson.set("result", result.getText());
        resultJson.set("type", result.getBarcodeFormat());
        bufferedImage.flush();
        return resultJson;
    }

    public static String pictureURL(String content) {
        int width = 300;
        int height = 200;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置背景颜色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        // 绘制一个圆形
        g2d.setColor(Color.RED);
        g2d.fillOval(100, 50, 100, 100);

        // 添加文字
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("宋体", Font.BOLD, 20));
        g2d.drawString(content, 100, 180);

        g2d.dispose();
        String base64Url = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64Encoded = Base64.getEncoder().encodeToString(imageBytes);
            base64Url = URLUtil.getDataUri(
                    "image/" + "png", "base64",
                    base64Encoded);
        }catch (Exception e){
            e.printStackTrace();
        }
        return base64Url;
    }

    public static String getBase64(String content){
        return content.replaceFirst(IMAGE_BASE64_PREFIX_PATTERN, "");
    }

    public static void main(String[] args) throws NotFoundException, IOException {
//        String str = getBarCode("aaaa");
//        System.out.println(str);
//        String content = getBase64(str);
//        JSONObject jsonObject = QRReader(content);
//        System.out.println(jsonObject);
//        System.out.println("=========================");
//        String strQR = getQrCode("bbbb");
//        System.out.println(strQR);
//        String contentQR = getBase64(strQR);
//        JSONObject jsonObjectQR = QRReader(contentQR);
//        System.out.println(jsonObjectQR);
        String picturedURL = pictureURL("新希望");
        System.out.println(picturedURL);
    }
}
